package com.yu.newsSys.listener;

import com.yu.newsSys.constants.ListenerConstants;
import com.yu.newsSys.constants.SessionConstants;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.List;
@WebListener
public class OnlineHttpSessionAttributeListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        HttpSession session = se.getSession();
        // 获取当前监听到的添加的name
        String name = se.getName();
        if (SessionConstants.USER_SESSION.equals(name)) {
            // 如果添加的是user属性,放入servletContext中的onlineList中
            String value = (String) se.getValue();
            ServletContext context = session.getServletContext();
            List<String> onlineList = (List<String>) context.getAttribute(ListenerConstants.ONLINE_LIST);
            onlineList.add(value);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
        HttpSession session = se.getSession();
        // 获取当前监听到的添加的name
        String name = se.getName();
        if (SessionConstants.USER_SESSION.equals(name)) {
            // 如果删除的是user属性,放入servletContext中的onlineList中
            String value = (String) se.getValue();
            ServletContext context = session.getServletContext();
            List<String> onlineList = (List<String>) context.getAttribute(ListenerConstants.ONLINE_LIST);
            onlineList.remove(value);
        }
    }
}
